﻿/*
 * SharePoint 2013 App Library
 *
 * Requires jQuery 1.7.1 or newer
 * Copyright (c) 2013 SharePoint Friends
 *
 * Licensed under the terms found in the Microsoft Office SharePoint 2013 App Store.
 * 
 * Requries : jquery.xml2json.js
 */
window.SF = window.SF || {};

window.SF.LicenseConstructor = function($) {
    var licenseCollection;
    var response;
    var licenseSettings;

    this.Check = function (s) {
        licenseSettings = s;
        var token = $.cookie(licenseSettings.productId);
        if (token) checkToken(token);
        else {
            licenseCollection = SP.Utilities.Utility.getAppLicenseInformation(licenseSettings.context, licenseSettings.productId);
            licenseSettings.context.executeQueryAsync(onRetrieveLicenseFromSPSuccess, onRetrieveLicenseFromSPFailure);
        }
    };

    function onRetrieveLicenseFromSPSuccess() {
        var topLicense;
        var encodedTopLicense;

        if (licenseCollection.get_count() > 0) {
            topLicense = licenseCollection.get_item(0).get_rawXMLLicenseToken();
            encodedTopLicense = encodeURIComponent(topLicense);
        } else {
            Redirect(licenseSettings.licenseUrl);
        }

        var request = new SP.WebRequestInfo();
        request.set_url("https://verificationservice.officeapps.live.com/ova/verificationagent.svc/rest/verify?token=" + encodedTopLicense);
        request.set_method("GET");
        response = SP.WebProxy.invoke(licenseSettings.context, request);
        licenseSettings.context.executeQueryAsync(onVerificationCallSuccess, onVerificationCallFailure);
    }

    function onRetrieveLicenseFromSPFailure(sender, args) {
        Redirect(licenseSettings.licenseUrl);
    }


    function onVerificationCallSuccess() {
        var xmltoken = response.get_body();
        $.cookie(licenseSettings.productId, xmltoken, {
            expires: 180
        });
        checkToken(xmltoken);
    }

    function checkToken(xmltoken) {
        var token = $.xml2json(xmltoken);

        switch (token.EntitlementType.toLowerCase()) {
            case "free":
                break;
            case "paid":
                break;
            case "trial":
                if (token.IsEntitlementExpired.toLowerCase() === "true") Redirect(licenseSettings.expiredUrl); // Trial app has expired!
                break;
        }
    }

    function onVerificationCallFailure() {
        Redirect(licenseSettings.licenseUrl);
    }

    function Redirect(url) {
        window.location.href = url;
    }
    return this;
};

window.SF.License = new SF.LicenseConstructor(jQuery);